<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use \app\admin\model\Domain;
use function EasyWeChat\Payment\get_client_ip;
use think\Loader;
use think\response\Json;
use think\Cache;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     *
     * 备案域名缓存5分钟，中转域名缓存10分钟，落地域名缓存5分钟
     * @return string
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     *
     */
    public function index()
    {
        $secret = $this->request->param('secret','');
        //防封请求
        if ($secret != ''){
            $userModel = new \app\admin\model\User();
            $user = Cache::get("user_".$secret);
            if ($user == null){
                $user = $userModel->where(['secret'=>$secret])->find();
                Cache::set("user_".$secret,$user,300);
            }

            if ($user == null){
//                $this->error("密钥错误","http://www.qq.com");
                $this->redirect("http://www.qq.com");
            }

            $model = new Domain();
            //主域名不再用于任何操作
            //$domain = $model->where(['uid'=>$user->id,'is_main_switch'=>1])->find();
            $sub_domain = Cache::get('sub_domain_'.$secret);
            if ($sub_domain == null){
                $sub_domain = $model->where(['uid'=>$user->id,'is_main_switch'=>0,'status'=>0])->order('id','asc')->find();
                Cache::set('sub_domain_'.$secret,$sub_domain,180);
            }

            if ($user['vip_expire_time'] == null || time() > strtotime($user['vip_expire_time'])){
//                $this->error("权限错误","http://www.qq.com");
                $this->redirect("http://www.qq.com");
                Cache::inc("auth_error",1);
            }

            if ($sub_domain == null){
//                $this->error("sub error ","http://www.qq.com");
                $this->redirect("http://www.qq.com");
            }
            Loader::import('wxpay.WxPayPubHelper');
            global $content;
            $content['wxappid'] = $user['wxappid'];
            $content['AppSecret'] = $user['AppSecret'];
            $content['wxmchid'] = $user['wxmchid'];
            $jsapi = new \JsApi_pub();
            $code = input('get.code');
            $url = $user->domain;
            if (!$code){
                //准备跳转到微信并返回当前页面获取code
                $rurl = "http://" . $url . "?".$_SERVER['QUERY_STRING'];
                $codeurl = $jsapi->createOauthUrlForCode(urlencode($rurl));
                $html = "<script>window.location.replace('".$codeurl."');</script>";
                return $html;
            }else{
                //$jsapi->setCode($code);
                //$ourl = $jsapi->createOauthUrlForOpenid();
                //$data = file_get_contents($ourl);//获取openid
                //$data = json_decode($data,true);
                $pathinfo = $this->request->param('pathinfo');
                $suffix = $pathinfo?$pathinfo:$_SERVER['QUERY_STRING'];
                if ($suffix == base64_encode(base64_decode($suffix))){//是base64
                    $suffix = base64_decode($suffix);
                }
                $reurl = "http://" . $sub_domain['domain'] ."/".$suffix;
                $html = "<script>window.location.replace('".$reurl."');</script>";
//                $this->redirect($reurl);
                return $html;
            }
        }else{
            // $domains = Cache::get("domains",[]);
            // $host = $this->request->server('HTTP_HOST');
            // if (in_array($host,$domains)){
            //     return header("HTTP/1.1 500 Internal Server Error");
            // }
            return view();
        }
    }

    /**
     * http://dlyhow.cn/url/user.php?uid=85&tzid=1&1from=qqllq&to=wx&pid=yszt.html&time=1566564402
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    //思路
    //备案域名请求->1类炮灰为微信公众号域名->由微信跳转回来后->2类炮灰域名->通过CURL或者ajax获取目的地网页
    //备案域名直接设置为1类炮灰域名 是错误的.会导致被封。
    public function jump_1()
    {
        //http://www.qoeovtc29.cn 从这里进入
        $secret = $this->request->request('secret');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where(['secret'=>$secret])->find();
        if ($user == null){
            $this->error("密钥错误");
        }
        if ($user->vip_expire_time < date("Y-m-d H:i:s")){
            $this->error("没有权限访问");
        }
        $domainModel = new Domain();
        $main_domain = $domainModel->where(['is_main_switch'=>1,'uid'=>$user->id])->find();
        global $content;
        $content['wxappid'] = $user['wxappid'];
        $content['AppSecret'] = $user['AppSecret'];
        $content['wxmchid'] = $user['wxmchid'];
        Loader::import('wxpay.WxPayPubHelper');
        $jsapi = new \JsApi_pub();
        $code = input('get.code');
        $url = $main_domain->domain;
        if (!$code){
            //准备跳转到微信并返回当前页面获取code
            $rurl = "http://" . $url . "?".$_SERVER['QUERY_STRING'];
            $codeurl = $jsapi->createOauthUrlForCode($rurl);
            $this->redirect($codeurl);
        }else{
            //$jsapi->setCode($code);
            //$ourl = $jsapi->createOauthUrlForOpenid();
            //$data = file_get_contents($ourl);//获取openid
            //$data = json_decode($data,true);
            $sub_domain = $domainModel->where(['uid'=>1,'is_main_switch'=>0,'status'=>0])->order('id','asc')->find();
            $reurl = "http://" . $sub_domain['domain'] . "/index/show/?".$_SERVER['QUERY_STRING'];
            $this->redirect($reurl);
        }
    }

    /**
     *
     * http://dlyhow.cn/url/user.php?uid=85&tzid=1&1from=qqllq&to=wx&pid=yszt.html&time=1566564402
     * 通过一类域名跳转的请求，在二类域名中输出最终结果。
     * @deprecated 这个方法暂停使用 这个操作方式易被恶意调用并且无法管控
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function show()
    {
        $secret = $this->request->param('secret');
        $userModel = new \app\admin\model\User();
        $user = $userModel->where(['secret'=>$secret])->find();
        if ($user == null){
            $this->error("密钥错误");
        }
        if ($user->vip_expire_time < date("Y-m-d H:i:s")){
            $this->error("没有权限访问");
        }
        $url = $this->request->param('url','');
        if ($url == ''){
            $this->error('参数错误');
        }
        $this->assign('url',$url);
        $this->assign('title',$this->request->param('title',''));
        $temp = $this->fetch();
        $data =  escape($temp);
        $this->assign('data',$data);
        return $this->fetch('showtime');
    }


    public function charge()
    {
        $price  = $this->request->param('price');
        $uid    = $this->request->param('uid');
        echo "缓慢开发中...";
//        echo $price . "--".$uid;
    }


    public function jump()
    {
	    $model = new \app\admin\model\Domain();
        $domain = $model->where(['domain'=>$_SERVER['SERVER_NAME']])->find();
        if ($domain){
            $domainList =  $model->where(['is_main_switch'=>0, 'status'=>0, 'uid'=>$domain['uid']])->select();
            if (!empty($domainList)){
                $this->success("准备中，请稍后","http://".$domainList[0]['domain'],'ds',3);
            }
        }else{
            $this->error("无法确定终点");
        }

    }

    public function test(){
        // $this->success("123","http://domain.lotus-wallet.com/index/index/test","",30);
        
         $headers = file_get_contents("https://mp.weixin.qq.com/mp/readtemplate?t=pages/wapredirect&url=http%3A%2F%2Fwww.bejejn.cn");
        //  echo "<pre>";
         print_r($headers);
        //  echo "</pre>";
    }


    public function sendWxMsg()
    {
        $name = input('name','');
        $msg = input('msg','');
        $secret = input('secret');

        $userModel = new \app\admin\model\User();
        $user = $userModel->where(['secret'=>$secret])->find();
        if (!$user){
            $this->error('secret error');
        }
        //
        $access_token = Cache::get('access_token_'.$secret,'');
        if ($access_token == ''){
            $acc_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$user['wxappid']."&secret=".$user['AppSecret'];
            $access_token = json_decode(file_get_contents($acc_url),true)['access_token'];
            Cache::set('access_token_'.$secret,$access_token,7200);
        }

        $msg_url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;

        $data = [];
        $data['touser'] = $user['openid'];
        $data['template_id'] = 'DZGeEDsfkxUdTlRZKmpfHITiq4fVRV-ofcGc6YRCH04';
        $data['data']['fitst'] = ['value'=>'服务器异常'];
        $data['data']['keyword1'] = ['value'=>$name];
        $data['data']['keyword2'] = ['value'=>'订单错误'];
        $data['data']['keyword3'] = ['value'=>$msg];
        $data['data']['remark'] = ['value'=>'监控服务检测空窗期超过阈值，请尽快检修。'];
        $data = getCurl($msg_url,json_encode($data));
        if (json_decode($data,true)['errcode'] == 0){
            return 'ok';
        }
    }

}
